package com.dongdongshop.config;


import cn.hutool.core.util.StrUtil;
import com.dongdongshop.exception.LoginException;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.SellerService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class LoginRealm<LzMenuService> extends AuthorizingRealm {

    @DubboReference
    private SellerService tbSellerService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        System.out.println("授权方法");
//        获取当前登录的用户
//        LzPerson person = (LzPerson) SecurityUtils.getSubject().getPrincipal();
//        //根据id查出来此id所拥有的权限
//        List<String> list = ms.getPermsById(person.getPid());
//        将这些权限添加
//        simpleAuthorizationInfo.addStringPermissions(list);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证方法");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        TbSeller tbSeller = tbSellerService.getAdminById(token.getUsername());//根据名字查询
        TbSeller tbSeller1 = tbSellerService.getAdminByEmail(token.getUsername());//根据邮箱查询
        TbSeller tbSeller2 = tbSellerService.getAdminByTel(token.getUsername());//根据手机号查询

        if (tbSeller != null){
            if (!tbSeller.getStatus().equals("0") && !StrUtil.isBlank(tbSeller.getStatus())){
                return new SimpleAuthenticationInfo(tbSeller, tbSeller.getPassword(), ByteSource.Util.bytes(tbSeller.getSalt()), tbSeller.getName());
            }else {
                throw new LoginException("账户异常");
            }

        }
        if (tbSeller1 != null){
            if (!tbSeller1.getStatus().equals("0") && !StrUtil.isBlank(tbSeller1.getStatus())){
                return new SimpleAuthenticationInfo(tbSeller1, tbSeller1.getPassword(), ByteSource.Util.bytes(tbSeller1.getSalt()), tbSeller1.getName());
            }else {
                throw new LoginException("账户异常");
            }

        }
        if (tbSeller2 != null ){
            if (!tbSeller2.getStatus().equals("0") && !StrUtil.isBlank(tbSeller2.getStatus())){
                return new SimpleAuthenticationInfo(tbSeller2, tbSeller2.getPassword(), ByteSource.Util.bytes(tbSeller2.getSalt()), tbSeller2.getName());
            }else {
                throw new LoginException("账户异常");
            }
        }

        return null;
    }
}
